<template>
  <view class="add-package-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">添加包裹</text>
      <text class="page-subtitle">填写快递取件信息</text>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <!-- 取件码输入 -->
      <view class="form-item">
        <view class="form-label">
          <text class="label-text">取件码</text>
          <text class="required">*</text>
        </view>
        <input
          class="form-input"
          v-model="formData.pickupCode"
          placeholder="请输入取件码"
          placeholder-class="input-placeholder"
          maxlength="50"
        />
      </view>

      <!-- 快递公司选择 -->
      <view class="form-item">
        <view class="form-label">
          <text class="label-text">快递公司</text>
        </view>
        <picker
          mode="selector"
          :range="expressCompanyOptions"
          :value="expressCompanyIndex"
          @change="onExpressCompanyChange"
        >
          <view class="picker-view">
            <text class="picker-text" :class="{'placeholder': !formData.expressCompany}">
              {{ formData.expressCompany || '请选择快递公司（可选）' }}
            </text>
            <text class="picker-arrow">▼</text>
          </view>
        </picker>
      </view>

      <!-- 驿站位置选择 -->
      <view class="form-item">
        <view class="form-label">
          <text class="label-text">驿站位置</text>
          <text class="required">*</text>
        </view>
        <picker
          mode="selector"
          :range="locationOptions"
          :value="locationIndex"
          @change="onLocationChange"
        >
          <view class="picker-view">
            <text class="picker-text" :class="{'placeholder': !formData.location}">
              {{ formData.location || '请选择驿站位置' }}
            </text>
            <text class="picker-arrow">▼</text>
          </view>
        </picker>
      </view>

      <!-- 快速识别区域 -->
      <view class="quick-recognize-section">
        <view class="section-header">
          <text class="section-title">快速识别</text>
          <text class="section-subtitle">粘贴短信内容，自动识别取件信息</text>
        </view>
        
        <view class="paste-input-container">
          <textarea
            class="paste-input"
            v-model="smsText"
            placeholder="请粘贴快递短信内容，例如：&#10;【菜鸟驿站】您的包裹已到达，取件码：1234-56，请及时取件。"
            placeholder-class="input-placeholder"
            :maxlength="500"
            :auto-height="true"
            :show-confirm-bar="false"
          />
          <view class="input-actions">
            <button class="clear-btn" @click="clearSmsText" v-if="smsText">
              <text class="clear-icon">✕</text>
              <text class="clear-text">清空</text>
            </button>
            <button class="recognize-btn" @click="quickRecognize" :disabled="!smsText || isRecognizing">
              <text class="btn-icon">🔍</text>
              <text class="btn-text">{{ isRecognizing ? '识别中...' : '开始识别' }}</text>
            </button>
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <button class="submit-btn" @click="handleSubmit">
        <text class="submit-text">提交</text>
      </button>
    </view>

    <!-- 识别结果弹窗 -->
    <RecognitionResultModal
      :visible="showResultModal"
      :type="resultModalType"
      :title="resultModalTitle"
      :message="resultModalMessage"
      :pickupCode="resultModalData.pickupCode"
      :expressCompany="resultModalData.expressCompany"
      :location="resultModalData.location"
      :address="resultModalData.address"
      confirmText="知道了"
      @update:visible="showResultModal = $event"
      @close="handleResultModalClose"
      @confirm="handleResultModalConfirm"
    />
  </view>
</template>

<script>
import packageManager from '../../../utils/package-manager.js'
import smsListener from '../../../utils/sms-listener.js'
import RecognitionResultModal from '../../../components/RecognitionResultModal.vue'

export default {
  components: {
    RecognitionResultModal
  },
  
  data() {
    return {
      formData: {
        pickupCode: '',
        expressCompany: '',
        location: ''
      },
      expressCompanyOptions: [
        '中通快递',
        '圆通快递',
        '申通快递',
        '韵达快递',
        '顺丰快递',
        '京东物流',
        '百世快递',
        '德邦快递',
        '极兔速递',
        '其他快递'
      ],
      expressCompanyIndex: -1,
      locationOptions: [
        // 菜鸟系列
        '菜鸟驿站',
        '小区菜鸟驿站',
        // 丰巢系列
        '丰巢快递柜',
        // 其他驿站
        '妈妈驿站',
        '兔喜生活',
        '多多驿站',
        '公司前台',
        '代收点',
        '快递柜',
        '便利店',
        '其他驿站'
      ],
      locationIndex: 0,
      smsText: '',
      isRecognizing: false,
      // 识别结果弹窗
      showResultModal: false,
      resultModalType: 'success',
      resultModalTitle: '',
      resultModalMessage: '',
      resultModalData: {
        pickupCode: '',
        expressCompany: '',
        location: '',
        address: ''
      }
    }
  },

  onShow() {
    // 页面显示时，确保弹窗状态正确
    // 如果弹窗状态异常，强制关闭
    if (this.showResultModal && !this.resultModalTitle) {
      this.showResultModal = false
    }
  },

  onHide() {
    // 页面隐藏时，关闭弹窗并重置识别状态
    this.showResultModal = false
    this.isRecognizing = false
  },

  onUnload() {
    // 页面卸载时，清理所有状态
    this.showResultModal = false
    this.isRecognizing = false
  },

  methods: {
    // 快递公司选择变化
    onExpressCompanyChange(e) {
      this.expressCompanyIndex = e.detail.value
      this.formData.expressCompany = this.expressCompanyOptions[e.detail.value]
    },

    // 驿站位置选择变化
    onLocationChange(e) {
      this.locationIndex = e.detail.value
      this.formData.location = this.locationOptions[e.detail.value]
    },

    // 快速识别短信内容
    async quickRecognize() {
      if (!this.smsText || this.smsText.trim() === '') {
        uni.showToast({
          title: '请先粘贴短信内容',
          icon: 'none'
        })
        return
      }

      // 如果正在识别中，防止重复触发
      if (this.isRecognizing) {
        return
      }

      // 先关闭之前的弹窗（如果有）
      if (this.showResultModal) {
        this.showResultModal = false
        // 等待弹窗关闭动画完成
        await new Promise(resolve => setTimeout(resolve, 300))
      }

      this.isRecognizing = true

      try {
        // 使用 sms-listener 的提取方法
        const packageInfo = smsListener.extractPackageInfo(this.smsText.trim())

        if (packageInfo && packageInfo.pickupCode) {
          // 识别成功，自动填充表单
          this.formData.pickupCode = packageInfo.pickupCode

          // 如果识别到快递公司，自动选择
          if (packageInfo.expressCompany) {
            const expressIndex = this.expressCompanyOptions.findIndex(
              company => company === packageInfo.expressCompany
            )
            if (expressIndex !== -1) {
              this.expressCompanyIndex = expressIndex
              this.formData.expressCompany = packageInfo.expressCompany
            } else {
              // 如果不在选项中，使用"其他快递"
              const otherIndex = this.expressCompanyOptions.findIndex(c => c === '其他快递')
              if (otherIndex !== -1) {
                this.expressCompanyIndex = otherIndex
                this.formData.expressCompany = '其他快递'
              }
            }
          }

          // 如果识别到驿站位置，自动选择
          if (packageInfo.location) {
            // 精确匹配
            let locationIndex = this.locationOptions.findIndex(
              loc => loc === packageInfo.location
            )
            
            // 如果精确匹配失败，尝试模糊匹配（包含关系）
            if (locationIndex === -1) {
              locationIndex = this.locationOptions.findIndex(
                loc => loc.includes(packageInfo.location) || packageInfo.location.includes(loc)
              )
            }
            
            if (locationIndex !== -1) {
              this.locationIndex = locationIndex
              this.formData.location = this.locationOptions[locationIndex]
            } else {
              // 如果识别的位置不在选项中，使用"其他驿站"
              const otherIndex = this.locationOptions.findIndex(loc => loc === '其他驿站')
              if (otherIndex !== -1) {
                this.locationIndex = otherIndex
                this.formData.location = '其他驿站'
              } else {
                // 如果连"其他驿站"都没有，使用第一个选项
                this.formData.location = this.locationOptions[0]
              }
            }
          } else {
            // 如果没有识别到位置，使用第一个选项
            if (!this.formData.location) {
              this.formData.location = this.locationOptions[0]
            }
          }

          // 显示自定义弹窗
          this.resultModalType = 'success'
          this.resultModalTitle = '识别成功'
          this.resultModalMessage = ''
          this.resultModalData = {
            pickupCode: packageInfo.pickupCode,
            expressCompany: packageInfo.expressCompany || '',
            location: packageInfo.location || '',
            address: packageInfo.address || ''
          }
          this.showResultModal = true
        } else {
          // 识别失败
          this.resultModalType = 'error'
          this.resultModalTitle = '识别失败'
          this.resultModalMessage = '未能识别到取件码，请检查短信内容是否完整。'
          this.resultModalData = {}
          this.showResultModal = true
        }
      } catch (error) {
        console.error('识别失败:', error)
        // 识别出错
          this.resultModalType = 'error'
          this.resultModalTitle = '识别出错'
          // 优化错误信息格式，避免过长文本可能被截断
          this.resultModalMessage = '识别过程出现错误，请重试。'
          this.resultModalData = {}
          // 使用 $nextTick 确保 DOM 更新后再显示弹窗
          this.$nextTick(() => {
            this.showResultModal = true
          })
      } finally {
        // 确保识别状态被重置，即使出现异常
        this.isRecognizing = false
      }
    },

    // 清空短信输入
    clearSmsText() {
      this.smsText = ''
    },

    // 处理识别结果弹窗关闭
    handleResultModalClose() {
      this.showResultModal = false
      // 确保状态完全清理
      this.$nextTick(() => {
        if (this.showResultModal) {
          this.showResultModal = false
        }
      })
    },

    // 处理识别结果弹窗确认
    handleResultModalConfirm() {
      this.showResultModal = false
      // 确保状态完全清理
      this.$nextTick(() => {
        if (this.showResultModal) {
          this.showResultModal = false
        }
      })
    },

    // 表单验证
    validateForm() {
      if (!this.formData.pickupCode.trim()) {
        uni.showToast({
          title: '请输入取件码',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.location) {
        uni.showToast({
          title: '请选择驿站位置',
          icon: 'none'
        })
        return false
      }

      return true
    },

    // 提交表单
    handleSubmit() {
      if (!this.validateForm()) {
        return
      }

      try {
        // 使用 package-manager 添加包裹
        const newPackage = {
          pickupCode: this.formData.pickupCode.trim(),
          expressCompany: this.formData.expressCompany || '',
          location: this.formData.location
        }

        packageManager.addPackage(newPackage)

        uni.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 1500
        })

        // 延迟返回，让用户看到成功提示
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)

      } catch (error) {
        console.error('添加包裹失败:', error)
        uni.showToast({
          title: '添加失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
/* 主容器 */
.add-package-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #f7f8fc 0%, #eef1f7 100%);
  padding: 20rpx;
  box-sizing: border-box;
}

/* 页面标题 */
.page-header {
  text-align: center;
  padding: 40rpx 0;
}

.page-title {
  font-size: 48rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 12rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-subtitle {
  font-size: 24rpx;
  color: #9ca3af;
  display: block;
}

/* 表单容器 */
.form-container {
  background: white;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  margin: 20rpx 10rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

/* 表单项 */
.form-item {
  margin-bottom: 40rpx;
}

.form-label {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.label-text {
  font-size: 28rpx;
  color: #1f2937;
  font-weight: 500;
}

.required {
  color: #ff4d4f;
  margin-left: 8rpx;
  font-size: 28rpx;
}

/* 输入框 */
.form-input {
  width: 100%;
  height: 80rpx;
  padding: 0 24rpx;
  background: #f9fafb;
  border: 2rpx solid #e5e7eb;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #1f2937;
  box-sizing: border-box;
}

.input-placeholder {
  color: #9ca3af;
  font-size: 28rpx;
}

/* 选择器 */
.picker-view {
  width: 100%;
  height: 80rpx;
  padding: 0 24rpx;
  background: #f9fafb;
  border: 2rpx solid #e5e7eb;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
}

.picker-text {
  font-size: 28rpx;
  color: #1f2937;
}

.picker-text.placeholder {
  color: #9ca3af;
}

.picker-arrow {
  font-size: 20rpx;
  color: #9ca3af;
}

/* 快速识别区域 */
.quick-recognize-section {
  margin: 40rpx 0;
  padding: 30rpx;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-radius: 16rpx;
  border: 2rpx solid #bae6fd;
}

.section-header {
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #0369a1;
  display: block;
  margin-bottom: 8rpx;
}

.section-subtitle {
  font-size: 24rpx;
  color: #0284c7;
  display: block;
}

.paste-input-container {
  margin-bottom: 20rpx;
}

.paste-input {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  background: white;
  border: 2rpx solid #bae6fd;
  border-radius: 12rpx;
  font-size: 26rpx;
  color: #1f2937;
  line-height: 1.6;
  box-sizing: border-box;
  margin-bottom: 16rpx;
}

.input-actions {
  display: flex;
  gap: 16rpx;
  justify-content: flex-end;
}

.clear-btn {
  padding: 12rpx 24rpx;
  background: #f3f4f6;
  border: 2rpx solid #d1d5db;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 24rpx;
  color: #6b7280;
}

.clear-icon {
  font-size: 20rpx;
}

.clear-text {
  font-size: 24rpx;
}

.recognize-btn {
  padding: 12rpx 32rpx;
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  border: none;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  gap: 8rpx;
  color: white;
  font-size: 26rpx;
  font-weight: 500;
}

.recognize-btn .btn-icon {
  font-size: 24rpx;
}

.recognize-btn .btn-text {
  font-size: 26rpx;
  color: white;
  font-weight: 500;
}

.recognize-btn:disabled {
  background: #d1d5db;
  color: #9ca3af;
}

.recognize-btn:active:not(:disabled) {
  opacity: 0.8;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 90rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 40rpx;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
}

.submit-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.submit-text {
  font-size: 32rpx;
  color: white;
  font-weight: bold;
}
</style>
